package jhta;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Vector;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;

import java.awt.Color;
import java.awt.Component;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

import javax.swing.ImageIcon;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

public class ReturnInput extends JInternalFrame {
	DefaultTableModel model;
	MyTableRender render;
	/*TableRowSorter<TableModel> tSoter;*/

	Connection con;
	String[] t = {"No","반납예정일","대여자","대여일","도서제목","상태"};

	private int row=-1; // 테이블의 선택된 행의 숫자를 저장하는 변수. 
	private Vector<RentVo> rentSql;

	private JTextField search;
	private JTextField bookTitle;
	private JTextField rentName;
	private JTextField rentDay;
	private JTextField returnExpect;
	private JTextField returnDay;
	private JComboBox comboBox;
	private JButton btnSearch;
	private JScrollPane scrollPane;
	private JPanel panel;
	private JTable table;
	private JLabel label;
	private JLabel label_1;
	private JLabel label_2;
	private JLabel label_3;
	private JLabel label_4;
	private JLabel bookReturn;


	public ReturnInput() {
		super("반납",true, true, true, true);
		setDefaultCloseOperation(JInternalFrame.HIDE_ON_CLOSE);

		setBounds(100, 100, 707, 505);
		getContentPane().setLayout(null);
		getContentPane().add(getComboBox());
		getContentPane().add(getSearch());
		getContentPane().add(getBtnSearch());
		getContentPane().add(getScrollPane());
		getContentPane().add(getPanel());
		con = JavaDBConnection.getConn();

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");		
		returnDay.setText(sdf.format(new Date()));

		table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
		table.getColumnModel().getColumn(0).setPreferredWidth(40);
		table.getColumnModel().getColumn(1).setPreferredWidth(140);
		table.getColumnModel().getColumn(2).setPreferredWidth(62);
		table.getColumnModel().getColumn(3).setPreferredWidth(140);
		table.getColumnModel().getColumn(4).setPreferredWidth(230);
		table.getColumnModel().getColumn(5).setPreferredWidth(50);
		
		
		
	}
	private JComboBox getComboBox() {
		if (comboBox == null) {
			String[] t = {"검색조건","전체","대여자","책 제목","날짜"};

			comboBox = new JComboBox(t);
			comboBox.addItemListener(new ItemListener() {
				public void itemStateChanged(ItemEvent ie) {
					String check = (String)ie.getItem();
					if(check.equals("날짜")){
						SimpleDateFormat sd = new SimpleDateFormat("yy/MM/dd");
						search.setText("날짜 검색은 yy/mm/dd 형식으로 해주세요. ex) 오늘 -> "+sd.format(new Date()));
					}else if(check.equals("전체")){
						search.setText("전체 검색은 검색어와 상관없이, 미반납된 도서가 모두 검색됩니다.");
					}else if(check.equals("검색조건")){
						search.setText("검색조건을 선택해주세요, 미선택시 조건은 '전체'와 동일합니다.");
					}else if(check.equals("책 제목")){
						search.setText("책 제목을 입력해주세요. 제목의 일부분으로도 검색 가능합니다.");
					}else if(check.equals("대여자")){
						search.setText("대여자 이름을 입력해주세요.");
					}
				}
			});
			comboBox.setBounds(12, 11, 132, 21);
		}
		return comboBox;
	}
	private JTextField getSearch() {
		if (search == null) {
			search = new JTextField();
			search.addKeyListener(new KeyAdapter() {
				@Override
				public void keyPressed(KeyEvent ke) {
					if(ke.getKeyCode()==ke.VK_ENTER){
						rentSearch();
					}						
				}
			});
			search.addMouseListener(new MouseAdapter() {
				@Override
				public void mouseClicked(MouseEvent arg0) {
					search.setText("");
				}
			});
			search.setBounds(156, 9, 415, 25);
			search.setColumns(10);
		}
		return search;
	}
	private JButton getBtnSearch() {
		if (btnSearch == null) {
			btnSearch = new JButton("검색");
			btnSearch.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					rentSearch();
				}
			});
			btnSearch.setBounds(583, 10, 97, 23);
		}
		return btnSearch;
	}
	private JScrollPane getScrollPane() {
		if (scrollPane == null) {
			scrollPane = new JScrollPane();
			scrollPane.setBounds(12, 39, 668, 279);
			scrollPane.setViewportView(getTable());
		}
		return scrollPane;
	}
	private JPanel getPanel() {
		if (panel == null) {
			panel = new JPanel();
			panel.setBounds(12, 328, 668, 138);
			panel.setLayout(null);
			panel.add(getLabel());
			panel.add(getTextField_1_1());
			panel.add(getLabel_1());
			panel.add(getTextField_2_1());
			panel.add(getLabel_2());
			panel.add(getTextField_3_1());
			panel.add(getLabel_3());
			panel.add(getTextField_4_1());
			panel.add(getLabel_4());
			panel.add(getTextField_5_1());
			panel.add(getBookReturn());
		}
		return panel;
	}
	private JTable getTable() {
		if (table == null) {
			
			model = new DefaultTableModel(t, 0){
				public boolean isCellEditable(int rowIndex, int mColIndex) {
					return false;
				}
			};
			table = new JTable(model);
			table.addMouseListener(new MouseAdapter() {
				@Override
				public void mouseClicked(MouseEvent me) {
					row = table.getSelectedRow();

					bookTitle.setText(String.valueOf(table.getValueAt(row, 4)));
					rentName.setText(String.valueOf(table.getValueAt(row, 2)));
					rentDay.setText(String.valueOf(table.getValueAt(row, 3)));
					returnExpect.setText(String.valueOf(table.getValueAt(row, 1)));
					
					tbc();
				}
			});

			/*tSoter = new TableRowSorter(model);
			table.setRowSorter(tSoter);*/

		}
		return table;
	}
	private JLabel getLabel() {
		if (label == null) {
			label = new JLabel("제목");
			label.setHorizontalAlignment(SwingConstants.RIGHT);
			label.setBounds(12, 5, 62, 15);
		}
		return label;
	}
	private JTextField getTextField_1_1() {
		if (bookTitle == null) {
			bookTitle = new JTextField();
			bookTitle.setEditable(false);
			bookTitle.setColumns(10);
			bookTitle.setBounds(86, 0, 582, 25);
		}
		return bookTitle;
	}
	private JLabel getLabel_1() {
		if (label_1 == null) {
			label_1 = new JLabel("대여자");
			label_1.setHorizontalAlignment(SwingConstants.RIGHT);
			label_1.setBounds(12, 33, 62, 15);
		}
		return label_1;
	}
	private JTextField getTextField_2_1() {
		if (rentName == null) {
			rentName = new JTextField();
			rentName.setEditable(false);
			rentName.setColumns(10);
			rentName.setBounds(86, 28, 141, 25);
		}
		return rentName;
	}
	private JLabel getLabel_2() {
		if (label_2 == null) {
			label_2 = new JLabel("대여일자");
			label_2.setHorizontalAlignment(SwingConstants.RIGHT);
			label_2.setBounds(12, 61, 62, 15);
		}
		return label_2;
	}
	private JTextField getTextField_3_1() {
		if (rentDay == null) {
			rentDay = new JTextField();
			rentDay.setEditable(false);
			rentDay.setColumns(10);
			rentDay.setBounds(86, 56, 141, 25);
		}
		return rentDay;
	}
	private JLabel getLabel_3() {
		if (label_3 == null) {
			label_3 = new JLabel("반납예정일");
			label_3.setHorizontalAlignment(SwingConstants.RIGHT);
			label_3.setBounds(12, 89, 62, 15);
		}
		return label_3;
	}
	private JTextField getTextField_4_1() {
		if (returnExpect == null) {
			returnExpect = new JTextField();
			returnExpect.setEditable(false);
			returnExpect.setColumns(10);
			returnExpect.setBounds(86, 84, 141, 25);
		}
		return returnExpect;
	}
	private JLabel getLabel_4() {
		if (label_4 == null) {
			label_4 = new JLabel("반납일");
			label_4.setHorizontalAlignment(SwingConstants.RIGHT);
			label_4.setBounds(12, 117, 62, 15);
		}
		return label_4;
	}
	private JTextField getTextField_5_1() {
		if (returnDay == null) {
			returnDay = new JTextField();
			returnDay.setEditable(false);
			returnDay.setColumns(10);
			returnDay.setBounds(86, 112, 141, 25);
		}
		return returnDay;
	}
	private JLabel getBookReturn() {
		if (bookReturn == null) {
			bookReturn = new JLabel("");
			bookReturn.addMouseListener(new MouseAdapter() {
				@Override
				public void mouseClicked(MouseEvent e) {
					if(row==-1){
						JOptionPane.showMessageDialog(null, "검색 하신 후, 테이블에서 반납하실 행을 선택해주세요.");
					}else{
						returnBook();
					}

				}
			});
			bookReturn.setIcon(new ImageIcon(ReturnInput.class.getResource("/jhta/ImageFolder/return.png")));
			bookReturn.setBounds(233, 28, 435, 109);
		}
		return bookReturn;
	}
	public void rentSearch(){
		String combo_selected= (String)comboBox.getSelectedItem();
		String sql_search = "";
		String sql="";
		//이전에 선택 된 테이블의 row 정보를 초기화
		row=-1;
		//테이블 초기화			
		for(int i=model.getRowCount()-1;i>=0;i--){
			model.removeRow(i);
		}

		if(combo_selected.equals("전체")||combo_selected.equals("검색조건")){			
			sql_search = "select no, edate, member_no,ldate,book_no,round(edate-sysdate) from rent where ddate is null order by edate asc";
			makeSql(sql_search);
			//tableSet(sql_search);
		}else if(combo_selected.equals("책 제목")){			
			sql_search = "select no, edate, member_no,ldate,book_no,round(edate-sysdate) from rent inner join book on rent.book_no=book.no where book.name like '%"+search.getText().trim()+"%' and rent.ddate is null order by edate asc";
			makeSql(sql_search);			
		}else if(combo_selected.equals("대여자")){
			sql_search = "select no, edate, member_no,ldate,book_no,round(edate-sysdate) from rent inner join bookmember on rent.member_no=bookmember.no where bookmember.name='"+search.getText().trim()+"' and rent.ddate is null order by edate asc";
			makeSql(sql_search);
		}else if(combo_selected.equals("날짜")){
			sql_search = "select no, edate, member_no,ldate,book_no,round(edate-sysdate) from rent where to_char(edate) like '%"+search.getText()+"%' and ddate is null order by edate asc";
			makeSql(sql_search);
		}

		if(model.getRowCount()==0){
			JOptionPane.showMessageDialog(null, "검색된 도서대여 정보가 없습니다.");			
		}		
	}
	public void makeSql(String sql){		
		try{
			// 데이터를 역으로 접근할 때 필요한 정보들을 저장하기 위해 RentVo 를 사용하고 Vector<RentVo> 를 저장.
			rentSql = new Vector<>();
			PreparedStatement pstmt = con.prepareStatement(sql);			
			ResultSet rs = pstmt.executeQuery();
			while(rs.next()){				
				Vector rowdata = new Vector<>();
				//no, edate, member_no,ldate,book_no,round(edate-sysdate)
				
				//대여번호
				rowdata.add(rs.getInt("no"));
				//반납예정일
				rowdata.add(rs.getString("edate"));
				//대여자
				rowdata.add(findRentor(rs.getInt("member_no")));
				//대여일
				rowdata.add(rs.getString("ldate"));
				//도서제목
				rowdata.add(findBook(rs.getInt("book_no")));	
				//대여상태
				String book_state="";
				if(Integer.parseInt(rs.getString("ROUND(EDATE-SYSDATE)"))<0){
					book_state="연체";
				}else{
					book_state="대여중";
				}
				rowdata.add(book_state);
				model.addRow(rowdata);				
				// 데이터를 역으로 접근할 때 필요한 정보들을 저장하기 위해 RentVo 를 사용하고 Vector<RentVo> 를 저장.				
				rentSql.add(new RentVo(rs.getInt("No"), rs.getInt("book_no"), rs.getInt("member_no")));				
			}
			//ResultSet, PreparedStatement Close -> 안하면 나중에 Overflow 생깁니다.
			tbc();
			rs.close();
			pstmt.close();
		}catch(Exception ex){
			ex.printStackTrace();			
			JOptionPane.showMessageDialog(null, "makeSql() 에러! ");
		}
	}
	public String findRentor(int member_num){
		String str="";
		String sql = "select name from bookmember where no="+String.valueOf(member_num);
		try{
			PreparedStatement pst = con.prepareStatement(sql);
			ResultSet rs = pst.executeQuery();
			rs.next();
			str=rs.getString("name");
			rs.close();
			pst.close();
		}catch(Exception ex){
			ex.printStackTrace();
		}
		return str;
	}
	public String findBook(int book_num){
		String str="";
		String sql = "select name from book where no="+String.valueOf(book_num);
		try{
			PreparedStatement pst = con.prepareStatement(sql);
			ResultSet rs = pst.executeQuery();
			rs.next();
			str=rs.getString("name");
			rs.close();
			pst.close();
		}catch(Exception ex){
			ex.printStackTrace();
		}
		return str;
	}	
	public void returnBook(){
		String returnSql = "update rent set ddate=sysdate where ddate is null and no=? and member_no=? and book_no=?";
		try{
			PreparedStatement pstmt_return = con.prepareStatement(returnSql);
			//검색시 저장된 대여도서의 정보를 담은 Vector에 접근하여, 대여번호, 회원번호, 책번호를 가져와 SQL문을 완성하고, 검색하여 반납처리합니다.

			Iterator<RentVo> it = rentSql.iterator(); 
			while(it.hasNext()){				
				RentVo rv_it = it.next();
				if((int)table.getValueAt(row, 0)==rv_it.getrRentNo()){
					pstmt_return.setInt(1, rv_it.getrRentNo());
					pstmt_return.setInt(2, rv_it.getmCode());
					pstmt_return.setInt(3, rv_it.getbCode());
					pstmt_return.executeUpdate();
					String returnBookVolumn = "update book set volume=(volume+1) where no='"+rv_it.getbCode()+"'";
					PreparedStatement psRBV = con.prepareStatement(returnBookVolumn);
					psRBV.executeUpdate();
					psRBV.close();
				}
			}

			//테이블 초기화						
			for(int i=model.getRowCount()-1;i>=0;i--){
				model.removeRow(i);
			}

			//검색정보 저장한 Vector 초기화
			rentSql = new Vector<>();

			//텍스트필드 초기화			
			bookTitle.setText("");
			rentName.setText("");
			rentDay.setText("");
			returnExpect.setText("");

			//선택된 테이블 번호 초기화
			row=-1;

			//PreparedStatement Close : 안하면 Overflow 생깁니다.
			pstmt_return.close();


			JOptionPane.showMessageDialog(null, "정상적으로 반납처리 되었습니다.");

		}catch(Exception ex){
			ex.printStackTrace();
		}

	}
	public void tbc(){
		table.setDefaultRenderer(Object.class, new myColorRenderer());
	}
	public class myColorRenderer extends DefaultTableCellRenderer { 

		public Component getTableCellRendererComponent(JTable table, Object value,boolean isSelected,
				boolean hasFocus, int row, int column) 
		{ 

			Component comp = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); 

			String s = table.getModel().getValueAt(row, column).toString(); 

			//if구문의 내용은 테이블에 따라 다르니 적절한 코딩하여야 한다.
			//참고로 rowIndex, colIndex는 0부터 시작한다.
			if(s.equalsIgnoreCase("연체")){ 
				comp.setBackground(Color.RED); 
				comp.setForeground(Color.BLACK);
			}
			else if(s.equalsIgnoreCase("대여중")){ 
				comp.setBackground(Color.GREEN); 
				comp.setForeground(Color.BLACK); 
			}			
			else{
				comp.setBackground(Color.WHITE); 
				comp.setForeground(Color.black);  
			}

			return( comp ); 
		} 
	}


}
